<?php
class Agenda extends WotHub
{
    private $_modelAgenda;
    
    public function afficher() {
        $this->_pdo = new smartbokModele($this->bdd);
        $this->_modelAgenda = new Model_Agenda($this->_pdo, $this->appId);
        $this->_ajouterEvent();
        $this->listeEvent = $this->_modelAgenda->getEvent();
        
        $this->addTemplate('agenda.tpl.php');
        $mois = null;
        $annee = null;
        $params = $this->getParams();
        if (isset($params[0]) === true) {
            $mois = $params[0];
            $annee = $params[1];
        }         
        $this->calendrier = $this->_buildCalendar($mois, $annee); 
          
        $this->enteteCalendrier = $this->_buildEnteteCalendrier($mois, $annee);
        $this->inscriptions = $this->_modelAgenda->getMyInscription();
        $this->creationEvent = $this->_controlerCreationRole(Model_Agenda::AGENDA_CREATE_EVENT);
        $this->typeEvents = $this->_modelAgenda->getEventType();
        $this->agendaActions = $this->_modelAgenda->getAgendaAction($this->baseUri, $this->creationEvent);
    }
    
    private function _controlerCreationRole($type) {
        switch($_SESSION['clanInfo']['params'][$type]) {
            case Model_Clan::CR_EVENT_OFF:
                if ($_SESSION['accountInfo']['officier'] === 'ko') {
                    return false;
                }
            break;
        
            case Model_Clan::CR_TEAM_STRAT:
                if ($_SESSION['accountInfo']['strateur'] === 'ko') {
                    return false;
                }
            break;
            
            default:
                $verif = true;
            break;
        }
        return true;
    }
    
    private function _ajouterEvent() {
        if (isset($_POST['typeEvent']) === true) {
            $agendaId = $this->_modelAgenda->insererEvent();
            if (in_array($_POST['typeEvent'], array(10, 11)) === true) {
                header('Location:'.$this->baseUri.'Agenda/Ajouter/'.$agendaId);
            }
        }
        
    }
    
    public function traiterActionXHR() {
        $this->_pdo = new smartbokModele($this->bdd);
        $this->_modelAgenda = new Model_Agenda($this->_pdo, $this->appId);
        
        $params = $this->getParams();
        switch ($params[0]) {
        	case 1:
        	case 2:
        	case 3:
        	    $retour = $this->_modelAgenda->participerEvent($params[0], $params[1]);
	        break;
	        
        	case 5:
        	    $retour = $this->_modelAgenda->deleteEvent($params[1]);
	            break;
        	    
        }
        header('Content-Type: text/xml'); 
        echo "<?xml version=\"1.0\"?>\n";
        echo "<reserve>\n";
         
        echo '<donnee><id>'.$params[1].'</id><action>'.$params[0].'</action></donnee>';
        
        echo "</reserve>\n";
        $this->traiterAffichage = false;
        return true;
    }
    
    private function _buildCalendar($mois= null, $annee= null) {
        if (isset($mois) === false) {
            $mois = date('n');
            $annee = date('Y');
        }
        elseif (isset($annee) === false) {
            $annee = date('Y');
        }
        $timeMois = mktime(0, 0, 0, $mois, 1, $annee);
        $firstDay = date('N', $timeMois);
        $nbJourMoisPrecedent = date('t', $timeMois-24*3600);
        $moisPrecedent = date('m',$timeMois-24*3600);
        $anneePrecedent = date('Y',$timeMois-24*3600);
        $moisSuivant = date('m',mktime(0,0,0,$mois+1,1,$annee));
        $anneeSuivante = date('Y',mktime(0,0,0,$mois+1,1,$annee));
       
        $nbJourMois = date('t', $timeMois);
        $actif = false;

        $m = $moisPrecedent;
        $a = $anneePrecedent;
        for($j = 1; $j <= 7; $j++) {
            $jour = $nbJourMoisPrecedent - $firstDay + $j +  1;
            if ( $jour > $nbJourMoisPrecedent) {
                $jour = $j- $firstDay + 1; 
                $m = $mois;
                $a = $annee;
                $actif = true;
            }
            $calendrier[$j]['jour'] = $jour;
            $calendrier[$j]['actif'] = $actif;
            $calendrier[$j]['id'] = $a.str_pad($m, 2, '0', STR_PAD_LEFT).str_pad($jour, 2, '0', STR_PAD_LEFT);
        }
        $m = $mois;
        $a = $annee;
        for ($j = 8; $j <= 42; $j++) {
            $jour++;
            if ($jour > $nbJourMois) {
                $jour = 1;
                $a = $anneeSuivante;
                $m = $moisSuivant;
                $actif = false;
            }
            $calendrier[$j]['jour'] = $jour;
            $calendrier[$j]['actif'] = $actif;
            $calendrier[$j]['id'] = $a.str_pad($m, 2, '0', STR_PAD_LEFT).str_pad($jour, 2, '0', STR_PAD_LEFT);
        }
        $k = 1;
        $jourCourant = date('Ymd');
        for($li = 1; $li <= 6; $li++) {
            for($col = 1; $col <= 7; $col ++) {
                $calendrier[$k]['class'] ='';
                if ($calendrier[$k]['id'] === $jourCourant) {
                    $calendrier[$k]['class'] ='today';
                }
                $cal[$li][$col] = $calendrier[$k];
                $k++;
            }
        }
        return $cal;
    }
    
    private function _buildEnteteCalendrier($mois= null, $annee= null) {
        if (isset($mois) === false) {
            $mois = date('n');
            $annee = date('Y');
        }
        elseif (isset($annee) === false) {
            $annee = date('Y');
        }
        $timeMois = mktime(0, 0, 0, $mois, 1, $annee);
        for ($i = -2; $i <= 2; $i++) {
            $caption[$i]['texte'] = strftime('%B', mktime(0, 0, 0, $mois+$i, 1, $annee));
            $caption[$i]['valeur'] = date('n', mktime(0, 0, 0, $mois+$i, 1, $annee));
            $caption[$i]['annee'] = date('Y', mktime(0, 0, 0, $mois+$i, 1, $annee));
        }
        return $caption;
    }
    
    public function AfficherDetail() {
        $this->_pdo = new smartbokModele($this->bdd);
        $this->_modelAgenda = new Model_Agenda($this->_pdo, $this->appId);
        $clan = new Model_Clan($this->_pdo, $this->appId);
        
        $this->ajouterScript('js/team.js');
        
        $this->addTemplate('agendadetail.tpl.php');      
        $params = $this->getParams();
        $this->detail = $this->_modelAgenda->getDetailAgenda($params[0]);
        $this->_modelAgenda->enregistrerEquipe($params[0]);
        $this->filtres = $clan->getFiltresDetail($this->detail['event_id']);
        $this->addJsVar('filtres', json_encode($this->filtres));
        $this->dateEvent = $this->_formatDate($this->detail['date']);
        
        $this->team = $this->_addScore($this->_modelAgenda->getTeam($params[0]), true);
        $this->inscrits = $this->_minusTank($this->_modelAgenda->getDataInscrits($params[0]));
        $this->backup = $this->_minusTank($this->_modelAgenda->getDataInscrits($params[0], 2));
        $this->refus = $this->_modelAgenda->getDataInscrits($params[0], 3);
        $lstId = $this->inscrits+$this->backup+$this->refus;
        $this->pseudos = Model_Membre::getNickName(implode(',', array_keys($lstId)));
        $this->creationTeam = $this->_controlerCreationRole(Model_Agenda::AGENDA_CREATE_TEAM);
    }
    
    private function _addScore($lstId, $tabId = false) {
        if ($tabId === true) {
            foreach($lstId as $account => &$tankActif) {
                $tank = new Model_Tank($this->_pdo, $_SESSION['appId']);
                $tankActif['score'] = $tank->getScore($tankActif['tank_id'], $account);
            }
        }
        else {
            foreach ($lstId as $account => &$lstTank) {
                foreach($lstTank as &$tankActif) {
                    $tank = new Model_Tank($this->_pdo, $_SESSION['appId']);
                    $tankActif['score'] = $tank->getScore($tankActif['tank_id'], $account);
                }
            }
        }
        return $lstId;
    }
    
     private function _minusTank($liste) {
         foreach($liste as $idMembre => &$membre) {
             if (key_exists($idMembre, $this->team) === true) {
                 foreach ($membre as &$tank) {
                     if ($tank['tank_id'] === $this->team[$idMembre]['tank_id']) {
                         $tank = null;
                     }
                 }
             }
         }
         foreach ($liste as &$membre) {
             $membre = array_filter($membre);
         }
         return $this->_addScore($liste);
     }
     
     public function Ajouter() {
         $this->addTemplate('agendacreate.tpl.php');
         $this->ajouterScript('js/ajouterEvent.js');
         $this->_buildContexte();
         $this->detail = array('titre' => '', 
                               'visibilite' => '',
                               'limite' => '',
                               'heavy' => '',
                               'medium' => '',
                               'light' => '',
                               'td' => '',
                               'spg' => '');
         
         $clan = new Model_Clan($this->_pdo, $_SESSION['appId']);
         $this->clans = $clan->getClanList($_SESSION['clanInfo']['clan_id']);
         if (isset($_POST['frm_titre']) === true) {
            if ($this->_controlerDetail() === true){
                $retour = $clan->ajouterDetail($this->_params[0]);
                SmartbokMessage::addMessage(SmartbokMessage::INFO, 'événement ajouté.');
            }             
         }
     }
     
     function _controlerDetail() {
         $controle = true;
         if (isset($_POST['frm_visibilite']) !== true) {
             $controle = false;
             $obl = false;
         }
         foreach ($_POST as $champ => $valeur){
             if ($valeur === '') {
                 $controle = false;
                 $obl = false;
             }
             switch ($champ) {
                 case 'frm_titre':
                     if (strlen($valeur) > 70) {
                         SmartbokMessage::addMessage(SmartbokMessage::ERR, 'le titre est trop long');
                         $controle = false;
                     }
                     break;
         
                 default:
                     if(ctype_digit(strval($valeur)) === false) {
                         $entier = false;
                         $controle = false;
                     }
                     else {
                         if ($champ !== ('frm_limite') && $valeur > 10) {
                             $level = false;
                         }
                     }
                     break;
             }
         }
         if (isset($obl) === true && $obl === false){
             SmartbokMessage::addMessage(SmartbokMessage::ERR, 'Veuillez saisir l\'ensemble des champs');
         }
         if (isset($entier) === true && $entier === false){
             SmartbokMessage::addMessage(SmartbokMessage::ERR, 'La limite et les types de tanks doivent contenir des entiers');
         }
         if (isset($level) === true && $level === false){
             SmartbokMessage::addMessage(SmartbokMessage::ERR, 'le niveau des tanks ne doit pas dépasser 10');
         }
         return $controle;
     }
}